import React from 'react'
import ArticleNode from './ArticleNode'
import { hostname } from '../../config/host.config'
import axios from '../../config/axios'
import NullContent from '../NullContent'
import { message } from 'antd'

export default class ArticleList extends React.Component {
    constructor(props) {
        super(props)
        this.state = { pageNum: 1, blogList: [], scrollFlag: false, emptyFlag: false, emptyType: '' }
    }

    async getArticleList(path) {
        const res = await axios.get(hostname + '/' + path, {
            params: {
                page: this.state.pageNum,
                size: 5
            }
        })
        if (res.status === 200 && res.data.statusCode === 1) {
            let arr = this.state.blogList
            if (res.data.statusMsg.length === 0) {
                this.setState({ scrollFlag: true })
                return false
            }
            res.data.statusMsg.map((value) => {
                arr.push(value)
            })
            this.setState({ blogList: arr })
            return true
        }
        message.destroy()
        return true
    }

    scroll(path) {
        let timer = null
        window.addEventListener('scroll', () => {
            clearTimeout(timer)
            if (!this.refs.articleList) {
                return
            }
            const domHeight = this.refs.articleList.clientHeight
            const windowScrollY = window.scrollY
            const windowHeight = window.innerHeight
            if (windowScrollY + windowHeight > domHeight + 100) {
                if (this.state.scrollFlag) {
                    return
                }
                timer = setTimeout(() => {
                    const pageNum = this.state.pageNum + 1
                    this.setState({ pageNum: pageNum })
                    this.getArticleList(path)
                }, 50)
            }
        })
    }

    async componentDidMount() {
        if (this.props.type === "index") {
            const path = 'blog/list'
            this.getArticleList(path)
            this.scroll(path)
        } else if (this.props.type === "collect") {
            const path = 'blog/collect'
            await this.getArticleList(path)
            if (this.state.blogList.length === 0) {
                this.setState({ emptyFlag: true, emptyType: '你的收藏内容为空' })
            }
            this.scroll(path)
        }
    }

    render() {
        return (
            <div ref="articleList">
                {this.state.blogList.map((value, key) =>
                    (<ArticleNode blog={value.list} user={value.user} key={key} type={this.props.type} />)
                )}
                {this.state.emptyFlag ? <NullContent>{this.state.emptyType}</NullContent> : null}
            </div>
        )
    }
}